package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper  orderMapper;
    @Autowired
    private UserMapper  userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 判断begin是否大于end
        if (begin.isAfter(end)) {
            // 如果begin大于end
            throw new OrderBusinessException("开始时间不能大于结束时间");
        }
        // 获取dateList
        List<LocalDate> dateList = new ArrayList<>();
        while(begin.isBefore(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        // 装成字符串
        String dateListString = StringUtils.join(dateList, ",");
        // 获取turnoverList
                // 先获取所有的订单
        List<Orders> allOrders = orderMapper.list();
                // 查询营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 获取该日期的营业额
            Double turnover = 0.0;
            for (Orders orders : allOrders) {
                // 判断订单的创建时间是否在dateList中
                if (orders.getOrderTime().toLocalDate().equals(date)) {
                    // 营业额累加
                    turnover += orders.getAmount().doubleValue();
                }
            }
            turnoverList.add(turnover);
        }
        String turnoverListString = StringUtils.join(turnoverList, ",");
        return new TurnoverReportVO(dateListString, turnoverListString);
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 判断begin是否大于end
        if (begin.isAfter(end)) {
            // 如果begin大于end
            throw new BaseException("开始时间不能大于结束时间");
        }
        // 获取dateList
        List<LocalDate> dateList = new ArrayList<>();
        while(begin.isBefore(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        // 装成字符串
        String dateListString = StringUtils.join(dateList, ",");
        // 查询所有员工
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
       List<User> users = userMapper.list();
       for (LocalDate date : dateList) {
           int totalUser = 0;
           int newUser = 0;
           for (User user : users) {
               // 判断用户创建时间是否在dateList中
               if (!user.getCreateTime().toLocalDate().isAfter(date)) {
                   totalUser++;
               }
               if (user.getCreateTime().toLocalDate().equals(date)) {
                   newUser++;
               }
           }
           totalUserList.add(totalUser);
           newUserList.add(newUser);
        }
       String totalUserListString = StringUtils.join(totalUserList, ",");
       String newUserListString = StringUtils.join(newUserList, ",");
        return new UserReportVO(dateListString, totalUserListString, newUserListString);
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 判断begin是否大于end
        if (begin.isAfter(end)) {
            // 如果begin大于end
            throw new OrderBusinessException("开始时间不能大于结束时间");
        }
        // 获取dateList
        List<LocalDate> dateList = new ArrayList<>();
        while(begin.isBefore(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        // 装成字符串
        String dateListString = StringUtils.join(dateList, ",");

        // orderCountList validOrderCountList totalOrderCount validOrderCount orderCompletionRate
        // 每日订单数        每日有效订单数         订单总数            有效订单数       订单完成率
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCount1List = new ArrayList<>();
        int totalOrderCount = 0;
        int validOrderCount = 0;
        double  orderCompletionRate = 0.0;
        // 先获取所有的订单
        List<Orders> allOrders = orderMapper.list();
        // for循环遍历
        for (LocalDate date : dateList) {
            int orderCount = 0;
            int validOrderCount1 = 0;
            for (Orders orders : allOrders) {
                // 判断订单的创建时间是否在dateList中
                if (orders.getOrderTime().toLocalDate().equals(date)) {
                    orderCount++; // 每日订单数
                    totalOrderCount++;
                    // 判断订单的状态是否为已完成
                    if (Objects.equals(orders.getStatus(), Orders.COMPLETED)) {
                        validOrderCount1++; // 每日有效订单数
                        validOrderCount++; // 有效订单数
                    }
                }
            }
            orderCountList.add(orderCount);
            validOrderCount1List.add(validOrderCount1);
        }
        orderCompletionRate = (double) validOrderCount / totalOrderCount;
        String orderCountListString = StringUtils.join(orderCountList, ",");
        String validOrderCount1ListString = StringUtils.join(validOrderCount1List, ",");
        return OrderReportVO.builder()
                .dateList(dateListString)
                .orderCountList(orderCountListString)
                .validOrderCountList(validOrderCount1ListString)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量top10统计
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        // 判断begin是否大于end
        if (begin.isAfter(end)) {
            // 如果begin大于end
            throw new OrderBusinessException("开始时间不能大于结束时间");
        }
        // 查询从开始到结束期间top10
        //select name,count(name) from order_detail where order_detail.order_id in (select id from orders where order_time between '2025-05-24' and '2025-05-31') group by name order by count(name) desc limit 10;
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<Map<String, Object>> top10 = orderDetailMapper.top10(beginTime, endTime);
        List nameList = top10.stream().map(m -> m.get("name")).collect(Collectors.toList());
        String nameListString = StringUtils.join(nameList, ",");
        List numberList = top10.stream().map(m -> m.get("number")).collect(Collectors.toList());
        String numberListString = StringUtils.join(numberList, ",");
        return SalesTop10ReportVO.builder()
                .nameList(nameListString)
                .numberList(numberListString)
                .build();
    }

    /**
     * 导出运营数据excel
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        // 1、从数据库中查询运营数据-近30天的数据
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        LocalDateTime beginDateTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(endDate, LocalTime.MAX);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginDateTime, endDateTime);
        // 2、读取excel模板，插入数据
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            // 创建excel对象
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 获取sheet
            XSSFSheet sheet = excel.getSheetAt(0);
            // 设置数据
                sheet.getRow(1).getCell(1).setCellValue(beginDate+ " "+ endDate);
                // 第四行
                XSSFRow row4 = sheet.getRow(3);
                row4.getCell(2).setCellValue(businessDataVO.getTurnover()); //  营业额
                row4.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate()); //  订单完成率
                row4.getCell(6).setCellValue(businessDataVO.getNewUsers()); //  新增用户数
                // 第五行
                XSSFRow row5 = sheet.getRow(4);
                row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount()); // 有效订单数
                row5.getCell(4).setCellValue(businessDataVO.getUnitPrice()); // 平均客单价
                // 准备明细数据-近30天
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
                BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
                // 获取行
                XSSFRow row = sheet.getRow(7 + i);

                row.getCell(1).setCellValue(date.toString()); // 日期
                row.getCell(2).setCellValue(businessData.getTurnover()); // 营业额
                row.getCell(3).setCellValue(businessData.getValidOrderCount()); // 有效订单数
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate()); // 订单完成率
                row.getCell(5).setCellValue(businessData.getUnitPrice()); // 平均客单价
                row.getCell(6).setCellValue(businessData.getNewUsers()); //  新增用户数

            }
            // 3、客户端下载excel-通过输出流
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            excel.close();
            outputStream.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
